<?php
namespace app\model;

// use app\model\Region;
/*
 * 用户地址模型.
 */
class UserAddress extends \think\Model
{
    protected $table = 'user_address'; // 表名
    /**
     * 自动时间戳数据类型
     *
     * @var string
     */
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'create_at';
    protected $updateTime = 'update_at';

    protected $type = [
        'default' => 'boolean',
        'dist_id' => 'integer',
        'create_at' => 'integer',
        'update_at' => 'integer'
    ];
    protected $field = ['name', 'mobile', 'title', 'address', 'user_id', 'dist_id', 'postcode', 'default'];          // 允许写入字段
    // 查询范围
    public function scopeUser($query)
    {
        $query->where('user_id', request()->uid);
    }
    /*
     * 新增前
     */
    public static function onBeforeInsert($model)
    {
        $model->user_id = request()->uid;
    }   
    /*
     * 当前地址被设为默认地址时,别的地址取消默认设置
     */
    public static function onBeforeWrite($model)
    {
        if($model->default == 1 && $model->getOrigin('default') == 0){
            self::where([['user_id', '=', request()->uid], ['default', '=', 1]])->update(['default' => 0]);
        }
    }
}
